<?php
/**
 * User: bgl
 * Date: 2023/12/8
 * Time: 15:35
 */

namespace App\Http\Controllers\Amazon;


use App\Http\Controllers\Controller;
use App\Logic\Amazon\AdsApi\Authorize;
use App\Models\Basics\AmazonAccountAds;
use GuzzleHttp\Client;
use Exception;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function oAuth(Request $request)
    {
        $state = $request->get('state');
        $code = $request->get('code');
        if(!$state){
            return response()->json(['status' => false, 'message' => '授权状态码无效！']);
        }
        if(!$code){
            return response()->json(['status' => false, 'message' => '未获取到授权码！']);
        }
        $a = new Authorize();
        $cacheState = $a->parseState($state);
        $accountId = $cacheState['account_id'];
        if(!$cacheState['state'] || $state != $cacheState['state']){
            return response()->json(['status' => false, 'message' => '授权状态码失效！']);
        }
        $client = new Client();
        $response = $client->post('https://api.amazon.com/auth/o2/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'code' => $code,
                'redirect_uri' => Authorize::REDIRECT_URI,
                'client_id' => Authorize::CLIENT_ID,
                'client_secret' => Authorize::CLIENT_SECRET,
            ],
            'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
        ]);
        $body = $response->getBody();
        if($response->getStatusCode() == 200){
            $data = json_decode($body, true);
            $accountAds = AmazonAccountAds::query()->find($accountId);
            $accountAds->refresh_token = $data['refresh_token'];
            $accountAds->auth_status = 1;
            $accountAds->auth_at = date('Y-m-d H:i:s');
            $flag = $accountAds->save();
            return view('api-plat.amazon-ads.index')->with(['message' => $flag ? '授权成功！' : '授权失败！', 'id' => $accountId]);
        }else{
            report(new Exception('[账号ID:'.$accountId.',ErrorBody:]'.$body,$response->getStatusCode()));
            return view('api-plat.amazon-ads.index')->with(['message' => '授权失败！', 'id' => $accountId]);
        }
    }
}
